package com.tianzehua.netty.socketexample;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.UUID;

/**
 * server  handler {@link SimpleChannelInboundHandler}
 * @author tianzehua
 * @date  2019/03/08
 */
public class MyServerHandler extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws  Exception{
        /* 输出远程连接客户端地址，端口号，内容 */
        System.out.println("address:" + ctx.channel().remoteAddress()+ ", " +msg);
        Thread.sleep(5000);
        ctx.writeAndFlush("from server :" + UUID.randomUUID());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        /* 异常捕获 ，出现异常，一般会将这个连接关闭掉 */
        cause.getStackTrace();
        System.out.println("服务器端发生异常！" + cause.getStackTrace().toString());
        ctx.channel().close();
    }
}
